package com.zl.lib_base.base

import android.app.ActivityManager
import android.content.Context
import android.os.Process
import android.text.TextUtils
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.multidex.BuildConfig
import androidx.multidex.MultiDex
import androidx.multidex.MultiDexApplication
import com.alibaba.android.arouter.launcher.ARouter
import com.kingja.loadsir.core.LoadSir
import com.tencent.bugly.Bugly
import com.tencent.bugly.BuglyStrategy
import com.tencent.bugly.beta.Beta
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import com.tencent.bugly.crashreport.CrashReport.initCrashReport
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity
import com.zl.lib_base.loadsir.EmptyCallback
import com.zl.lib_base.loadsir.ErrorCallback
import com.zl.lib_base.loadsir.LoadingCallback
import com.zl.lib_base.utils.AppHelper
import com.zl.lib_base.utils.AppUtil
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.unit.Subunits
import java.util.*

/**
 * @Description: Application基类，负责初始化一些模块
 * @Author: ZL
 * @CreateDate: 2021/11/26 17:25
 */
open class BaseApplication : MultiDexApplication() {

    private var mActivityList: LinkedList<RxAppCompatActivity>? = null

    //让外部获取到BaseApplication
    companion object {
        @JvmStatic
        lateinit var instance: BaseApplication
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(base)
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        ProcessLifecycleOwner.get().lifecycle.addObserver(ApplicationLifecycleObserver())
        //初始化所有数据
        if (isAppMainProcess()) {
            onCreateMethod()
            initBugly()
            //组件化实例化
            initARouter()
            initLoadSir()
            AppHelper.init(this.applicationContext)
            //今日头条适配
            AutoSizeConfig.getInstance().setBaseOnWidth(true).setExcludeFontScale(true)
                .unitsManager.supportSubunits = Subunits.MM
        }
    }

    private fun initBugly() {
        Beta.autoInit = true
        val strategy = BuglyStrategy()
        strategy.appVersion = AppUtil.getVersionName(applicationContext)
        strategy.appChannel = "Debug"
        strategy.appPackageName = AppUtil.getPackageName(applicationContext)
        strategy.appReportDelay = 20000 //Bugly会在启动20s后联网同步数据

        // 测试阶段设置成true，发布时设置为false。
        Bugly.init(applicationContext, "8c8b467a1e", BuildConfig.DEBUG, strategy)
    }

    /**
     * 初始化操作
     */
    open fun onCreateMethod() {}

    private fun initARouter() {
        if (BuildConfig.DEBUG) { // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog() // 打印日志
            ARouter.openDebug() // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        ARouter.init(this) // 尽可能早，推荐在Application中初始化
    }

    private fun initLoadSir() {
        LoadSir.beginBuilder()
            .addCallback(ErrorCallback())
            .addCallback(LoadingCallback())
            .addCallback(EmptyCallback())
            .setDefaultCallback(LoadingCallback::class.java)
            .commit()
    }

    /**
     * 返回一个存储所有存在的activity的列表
     */
    fun getActivityList(): LinkedList<RxAppCompatActivity>? {
        if (mActivityList == null) mActivityList = LinkedList<RxAppCompatActivity>()
        return mActivityList
    }

    /**
     * 判断是不是UI主进程，因为有些东西只能在UI主进程初始化
     */
    private fun isAppMainProcess(): Boolean {
        return try {
            val pid = Process.myPid()
            val process = getAppNameByPID(applicationContext, pid)
            when {
                TextUtils.isEmpty(process) -> true
                packageName.equals(process, ignoreCase = true) -> true
                else -> false
            }
        } catch (e: Exception) {
            e.printStackTrace()
            true
        }
    }

    /**
     * 根据Pid得到进程名
     */
    private fun getAppNameByPID(context: Context, pid: Int): String {
        val manager =
            context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == pid) {
                return processInfo.processName
            }
        }
        return ""
    }

    override fun onTerminate() {
        super.onTerminate()
        ARouter.getInstance().destroy()
    }

    private inner class ApplicationLifecycleObserver : LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        private fun onAppForeground() {
            // TODO: "ApplicationObserver: app moved to foreground"
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        private fun onAppBackground() {
            // TODO: "ApplicationObserver: app moved to background"
        }
    }
}